(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('questionCountController', questionCountController);
    questionCountController.$inject = ['$scope', 'searchService', '$sce', 'questionCountService', 'kibanaPartition', 'ACTIVE'];

    function questionCountController($scope, searchService, $sce, questionCountService, kibanaPartition, active) {

        var currentTime = new Date();

        var slowServiceTop10Echart = echarts.init(angular.element('#slowServiceTop10Echart')[0]);
        var slowCommTop10Echart = echarts.init(angular.element('#slowCommTop10Echart')[0]);

        $scope.allArray = [];
        $scope.batchArray = [];
        $scope.xcomArray = [];
        $scope.sqlTop10 = 1;
        $scope.partition = '全部';
        $scope.show = [];
        $scope.code = [];
        $scope.partitionName = kibanaPartition;
        $scope.timeType = 'td';
        $scope.startTime = getToday00Clock().Format("yyyy-MM-ddThh:mm:ss.S");
        $scope.endTime = getToday11Clock().Format("yyyy-MM-ddThh:mm:ss.S");
        $scope.uid = "all";
        $scope.batchUid = "batch";
        $scope.xcomUid = "xcom";

        searchService.getPartition({}).then(
            function (resp) {
                $scope.partitionSource = toTree(resp.data);
                angular.forEach(resp.data, function (item) {
                    $scope.show.push(item.ename);
                });
                $scope.show.push('all');
                $scope.partitionName = kibanaPartition;
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                //  $scope.slowSqlGridOptions.dataSource.read();
            }, function (err) {
            }
        );
        $scope.selectShow = function (k) {

            if (k == 'all') {
                $scope.sqlTop10 = 1;
                $scope.partition = '全部';
                $scope.code = [];
                $scope.partitionName = kibanaPartition;
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                $scope.slowSqlGridOptions.dataSource.read();
            } else {
                $scope.sqlTop10 = 0;
                angular.forEach($scope.show, function (item) {
                    if (item == k.ename) {
                        $scope.partition = k.fname + "-" + k.cname;
                        $scope.partitionName = k.ename;
                    }

                });
                $scope.code = k.code;
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                $scope.batchGridOptions.dataSource.read();
                $scope.xcomGridOptions.dataSource.read();
                $scope.slowSqlGridOptions.dataSource.read();
            }

            $scope.win.close();
        };

        $scope.select = function () {
            if ($scope.timeType == 'td') {
                $scope.startTime = getToday00Clock().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getToday11Clock().Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '1h') {
                currentTime.setHours(currentTime.getHours() - 1);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '4h') {
                currentTime.setHours(currentTime.getHours() - 4);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '12h') {
                currentTime.setHours(currentTime.getHours() - 12);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == 'tw') {
                $scope.startTime = getWeekStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getWeekEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == 'tM') {
                $scope.startTime = getMonthStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getMonthEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == 'yd') {
                $scope.startTime =new Date(getToday00Clock().setDate(getToday00Clock().getDate()-1)).Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = new Date(getToday11Clock().setDate(getToday11Clock().getDate()-1)).Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == 'pw') {
                $scope.startTime = getLastWeekStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getLastWeekEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '1w') {
                currentTime.setDate(currentTime.getDate()-7);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '2w') {
                currentTime.setDate(currentTime.getDate()-14);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '3w') {
                currentTime.setDate(currentTime.getDate()-21);
                $scope.startTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == 'pM') {
                $scope.startTime = getLastMonthStartDate().Format("yyyy-MM-ddThh:mm:ss.S");
                $scope.endTime = getLastMonthEndDate().Format("yyyy-MM-ddThh:mm:ss.S");
                console.log($scope.startTime);
                console.log($scope.endTime);
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '1M') {
                currentTime.setMonth(currentTime.getMonth()-1);
                $scope.startTime = (currentTime.Format("yyyy-MM-ddThh:mm:ss.S"));
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '2M') {
                currentTime.setMonth(currentTime.getMonth()-2);
                $scope.startTime = (currentTime.Format("yyyy-MM-ddThh:mm:ss.S"));
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '3M') {
                currentTime.setMonth(currentTime.getMonth()-3);
                $scope.startTime = (currentTime.Format("yyyy-MM-ddThh:mm:ss.S"));
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            } else if ($scope.timeType == '6M') {
                currentTime.setMonth(currentTime.getMonth()-6);
                $scope.startTime = (currentTime.Format("yyyy-MM-ddThh:mm:ss.S"));
                currentTime = new Date();
                $scope.endTime = currentTime.Format("yyyy-MM-ddThh:mm:ss.S");
                querySlowServiceTop10("4. service end.");
                querySlowCommTop10("6. service end.");
                if ( $scope.sqlTop10 ==0 ){
                    $scope.batchGridOptions.dataSource.read();
                    $scope.xcomGridOptions.dataSource.read();
                }
                $scope.slowSqlGridOptions.dataSource.read();
            }
        };
        $scope.slowSqlColumns = [
            {field: "logmsg", title: "SQL", width: "600px"},
            {field: "partition", title: "分区名", width: "100px"},
            {field: "service", title: "服务名", width: "200px"},
            {field: "execTime", title: "时间(ms)", width: "100px"}
        ];
        $scope.slowSqlGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: $scope.slowSqlColumns,
            toolbar: ["excel"],
            excel: {
                fileName: "慢SQLTop10.xlsx",
                filterable: true
            },
        };
        $scope.slowSqlGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    questionCountService.querySlowSqlTop10($scope.partitionName, $scope.uid, $scope.startTime, $scope.endTime, $scope.code, active).then(function (resp) {
                        $scope.allArray = [];
                        angular.forEach(resp, function (item) {
                            $scope.allArray.push(item);
                        })
                        e.success($scope.allArray);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {

            },
            schema: {
                model: $scope.ELKModel
            }
        });
        $scope.batchColumns = [
            {field: "logmsg", title: "SQL", width: "600px"},
            {field: "partition", title: "分区名", width: "100px"},
            {field: "service", title: "服务名", width: "200px"},
            {field: "execTime", title: "时间(ms)", width: "100px"}

        ];
        $scope.batchGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: $scope.batchColumns,
            toolbar: ["excel"],
            excel: {
                fileName: "批处理慢SQLTop10.xlsx",
                filterable: true
            }
        };
        $scope.batchGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {

                    questionCountService.querySlowSqlTop10($scope.partitionName, $scope.batchUid, $scope.startTime, $scope.endTime, $scope.code).then(function (resp) {
                        $scope.batchArray = [];
                        angular.forEach(resp, function (item) {
                            $scope.batchArray.push(item);
                        })
                        e.success($scope.batchArray);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {

            },
            schema: {
                model: $scope.ELKModel
            }
        });
        $scope.xcomColumns = [
            {field: "logmsg", title: "SQL", width: "600px"},
            {field: "partition", title: "分区名", width: "100px"},
            {field: "service", title: "服务名", width: "200px"},
            {field: "execTime", title: "时间(ms)", width: "100px"}
        ];
        $scope.xcomGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: $scope.xcomColumns,
            toolbar: ["excel"],
            excel: {
                fileName: "电文慢SQLTop10.xlsx",
                filterable: true,

            }
        };
        $scope.xcomGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    questionCountService.querySlowSqlTop10($scope.partitionName, $scope.xcomUid, $scope.startTime, $scope.endTime, $scope.code).then(function (resp) {
                        $scope.xcomArray = [];
                        angular.forEach(resp, function (item) {
                            $scope.xcomArray.push(item);
                        })
                        e.success($scope.xcomArray);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {

            },
            schema: {
                model: $scope.ELKModel
            }
        });

        /**
         * get partition data
         */


        //慢服务Top10
        function querySlowServiceTop10(logmsg) {
            questionCountService.querySlowServiceOrCommTop10($scope.partitionName, logmsg, $scope.startTime, $scope.endTime, $scope.code, active).then(
                function (resp) {

                    var slowServiceTop10Data = resp;
                    slowServiceTop10Analysis(slowServiceTop10Data, $scope.partitionName)
                }, function (error) {
                    console.log(error);
                    notify('error', '失败', error.message);
                });
        }

        function slowServiceTop10Analysis(slowServiceTop10Data, partition) {

            var xTime = [];
            var yCount = [];
            if (slowServiceTop10Data.length != 0) {
                angular.forEach(slowServiceTop10Data, function (item) {
                        xTime.push(item.service);
                        yCount.push((item.execTime) / 1000);
                    }
                );
                var slowServiceTop10Option = {

                    color: ['#05d89a'],
                    title: {
                        text: partition + "慢服务Top10",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    },
                    legend: {
                        left: "right",
                        data: ['Service执行时间(秒)']
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function (params) {
                            var res = "";
                            angular.forEach(params, function (item) {
                                res += "<span >Service执行时间(秒):" + "&emsp;" + item.value + '</span>' + '<br>' + '<hr>'
                                    + "<span>Service名:" + "&emsp;&emsp;&emsp;&emsp;" + item.name + "</span>"
                            });
                            return res;
                        }
                    },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '8%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: xTime,
                            name: 'Service名',
                            nameLocation: "center",
                            nameGap: 100,
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: {
                                rotate: 45
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            //name:"",
                            nameRotate: "90",
                            nameLocation: "center",
                            nameGap: 40,
                            splitLine: { //网格线
                                show: true
                            },
                            textStyle: {
                                fontSize: 14,
                                fontWeight: "bold",
                            }
                        }
                    ],
                    series: [
                        {
                            name: 'Service执行时间(秒)',
                            type: 'bar',
                            barWidth: '60%',
                            barMinHeight: 1,
                            data: yCount
                        }
                    ]

                }
                slowServiceTop10Echart.setOption(slowServiceTop10Option, true);
            } else {
                var slowServiceTop10Option = {
                    title: {
                        text: partition + "慢服务Top10",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    },
                    noDataLoadingOption: {
                        text: '暂无数据',
                        effect: 'bubble',
                        effectOption: {
                            effect: {
                                n: 0
                            }
                        }
                    }
                };
                slowServiceTop10Echart.setOption(slowServiceTop10Option, true);
            }
            ;
        }

        //慢电文Top10
        function querySlowCommTop10(logmsg) {
            questionCountService.querySlowServiceOrCommTop10($scope.partitionName, logmsg, $scope.startTime, $scope.endTime, $scope.code, active).then(
                function (resp) {

                    var slowCommTop10Data = resp;
                    slowCommTop10Analysis(slowCommTop10Data, $scope.partitionName);
                }, function (error) {
                    console.log(error);
                    notify('error', '失败', error.message);
                });
        }

        function slowCommTop10Analysis(slowCommTop10Data, partition) {

            var xTime = [];
            var yCount = [];
            if (slowCommTop10Data.length != 0) {
                angular.forEach(slowCommTop10Data, function (item) {
                        xTime.push(item.service);
                        yCount.push((item.execTime) / 1000);
                    }
                );
                var slowCommTop10Option = {

                    color: ['#6F87D8'],
                    title: {
                        text: partition + "慢电文Top10",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    },
                    legend: {
                        left: "right",
                        data: ['Service执行时间(秒)']
                    },
                    tooltip: {
                        trigger: 'axis',
                        axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                            type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                        },
                        formatter: function (params) {
                            var res = "";
                            angular.forEach(params, function (item) {
                                res += "<span >Service执行时间(秒):" + "&emsp;" + item.value + '</span>' + '<br>' + '<hr>'
                                    + "<span>Service名:" + "&emsp;&emsp;&emsp;&emsp;" + item.name + "</span>"
                            });
                            return res;
                        }
                    },
                    grid: {
                        left: '4%',
                        right: '4%',
                        bottom: '8%',
                        containLabel: true
                    },
                    xAxis: [
                        {
                            type: 'category',
                            data: xTime,
                            name: 'Service名',
                            nameLocation: "center",
                            nameGap: 100,
                            axisTick: {
                                alignWithLabel: true
                            },
                            axisLabel: {
                                rotate: 45
                            }
                        }
                    ],
                    yAxis: [
                        {
                            type: 'value',
                            nameRotate: "90",
                            nameLocation: "center",
                            nameGap: 40,
                            splitLine: { //网格线
                                show: true
                            },
                            textStyle: {
                                fontSize: 14,
                                fontWeight: "bold",
                            }
                        }
                    ],
                    series: [
                        {
                            name: "Service执行时间(秒)",
                            type: 'bar',
                            barWidth: '60%',
                            barMinHeight: 1,
                            data: yCount
                        }
                    ]

                }
                slowCommTop10Echart.setOption(slowCommTop10Option, true);
            } else {
                var slowCommTop10Option = {
                    title: {
                        text: partition + "慢电文Top10",
                        textStyle: {
                            color: "#6d6d6d",
                            fontSize: 15,
                            fontWeight: "bold",
                            top: "2%"
                        }
                    }
                };
                slowCommTop10Echart.setOption(slowCommTop10Option, true);
            }
            ;


        }

        //图表自适应
        window.onresize = function () {
            slowServiceTop10Echart.resize();
            slowCommTop10Echart.resize();

        }
    }


})();
